package com.kkb.controller;

import com.kkb.bean.Message;
import com.kkb.bean.Result;
import com.kkb.bean.TableUser;
import com.kkb.bean.User;
import com.kkb.mvc.ResponseBody;
import com.kkb.service.AdminService;
import com.kkb.service.CourierService;
import com.kkb.service.UserService;
import com.kkb.utils.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class UserController {

    @ResponseBody("/wx/loginSms.do")
    public String wx_login(HttpServletRequest request, HttpServletResponse response){
        // 获取手机号码
        String userPhone = request.getParameter("userPhone");
        // 发送验证码
//        String code = RandomUtil.getCode()+"";
        String code = "666666";
        // 全部置为666666 难敲
        boolean res = SMSUtil.sendLoginCode(userPhone, code);
        UserUtil.setUserCode(request.getSession(),userPhone,code);
        Message message = null;
        if (res) {
            message = new Message(0,"验证码发送成功");
        } else{
            message = new Message(-1,"验证码发送失败");
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        boolean flag = false;// 标志是否成功

        // 获取手机号码
        String userPhone = request.getParameter("userPhone");
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        // 准备消息对象
        Message message = null;
        // 登录成功 判断是否有该用户，没有就注册，有就更新登录时间
        if (code.equals(UserUtil.getUserCode(session,userPhone))) {
            // 判断是快递员登录还是用户登录
            boolean courier = CourierService.isExist(userPhone);
            if (courier){
                System.out.println("???快递员");
                // 是快递员
                // 保存信息
                UserUtil.setUserInfo(session,new User(userPhone,false));
                if (CourierService.updateLoginInfo(userPhone)) {
                    message = new Message(1,"登录成功");
                    flag = true;
                } else {
                    message = new Message(-1,"登录失败");
                }
            } else {
                System.out.println("???用户");
                // 用户
                boolean login = UserService.isLogin(userPhone);
                if (login) {
                    System.out.println("已经注册");
                    // 已经注册
                    UserUtil.setUserInfo(session,new User(userPhone,true));
                    UserService.updateLoginTimeAndIp(userPhone,new Date(),request.getRemoteAddr());
                    message = new Message(0,"登录成功");
                    flag = true;
                } else {
                    // 注册
                    boolean register = UserService.register(userPhone);
                    if (register) {
                        // 保存信息
                        UserUtil.setUserInfo(session,new User(userPhone,true));
                        message = new Message(0,"登录成功");
                        flag = true;
                    } else {
                        // 登录失败
                        message = new Message(-1,"登录失败");
                    }
                }
            }
        } else if (UserUtil.getUserCode(session,userPhone) == null) {
            // 手机号码错误
            message = new Message(-1,"手机号码未获取到短信");

        } else if (!code.equals(UserUtil.getUserCode(session,userPhone))) {
            // 验证码错误
            message = new Message(-2,"验证码不一致");
        }

        // 登入成功设置cookie
        if (flag) {
            System.out.println("我已经设置cookie");
            // 设置cookie
            Cookie userCookie = new Cookie("user_cookie", userPhone);
            System.out.println(userPhone);
            // 设置cookie的时间 --3分钟
            userCookie.setMaxAge(1*60*3);
            //
            userCookie.setPath("/");
            // 添加cookie
            response.addCookie(userCookie);

        }

        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/userInfo.do")
    public String userInfo(HttpServletRequest request, HttpServletResponse response){
        User userInfo = UserUtil.getUserInfo(request.getSession());
        Message message = null;
        if (userInfo.isUser()){
            message = new Message(0,userInfo.getPhoneNumber());
        } else{
            message = new Message(1,userInfo.getPhoneNumber());
        }
        return JSONUtil.toJSON(message);
    }

    @ResponseBody("/wx/logout.do")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        // 1. 销毁session
        request.getSession().invalidate();
        // 2. 回复消息
        return JSONUtil.toJSON(new Message(0));
    }

    @ResponseBody("/user/list.do")
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        int offset = Integer.parseInt(request.getParameter("offset"));
        int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        List<User> list = UserService.findList(true, offset, pageNumber);
        List<TableUser> newList = new ArrayList<>();
        // 数据转换
        for (User user : list) {
            String loginTime =  user.getLoginTime()==null ? "未登录":DateFormatUtil.format(user.getLoginTime()).substring(0,10);
            String createTime = DateFormatUtil.format(user.getCreatTime()).substring(0,10);
            String password = "********";
            TableUser tableUser = new TableUser(user.getId(), user.getUsername(), password, user.getIdCard(), user.getPhoneNumber(), user.getLoginIp(), loginTime, createTime);
            newList.add(tableUser);
        }

        // 获取总数
        Map<String, Integer> map = UserService.console();
        Result<TableUser> result = new Result<>(newList,map.get("data1"));
        return JSONUtil.toJSON(result);
    }

    @ResponseBody("/user/insert.do")
    public String insert(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String idCard = request.getParameter("idCard");
        String password = request.getParameter("password");
        boolean insert = UserService.insert(new User(username, password, idCard, phone));
        Message e = null;
        if (insert){
            e = new Message(0,"添加成功");
        } else{
            e = new Message(-1,"添加失败");
        }
        return JSONUtil.toJSON(e);
    }

    @ResponseBody("/user/update.do")
    public String update(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String idCard = request.getParameter("idCard");
        String password = request.getParameter("password");
        int id = Integer.parseInt(request.getParameter("id"));
        boolean update = UserService.update(id, new User(username, password, idCard, phone));

        Message e = null;
        if (update){
            e = new Message(0,"修改成功");
        } else{
            e = new Message(-1,"修改失败");
        }
        return JSONUtil.toJSON(e);
    }

    @ResponseBody("/user/find.do")
    public String find(HttpServletRequest request, HttpServletResponse response){
        String phone = request.getParameter("phone");
        User user = UserService.findByPhoneNumber(phone);
        Message e = null;
        if (user == null){
            e = new Message(-1,"没有该用户");
        } else {
            e = new Message(0,"查询成功",user);
        }
        return JSONUtil.toJSON(e);
    }

    @ResponseBody("/user/delete.do")
    public String delete(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        boolean delete = UserService.delete(id);
        Message message = null;
        if (delete) {
            message = new Message(0,"删除成功");
        } else{
            message = new Message(-1,"删除失败");
        }
        return JSONUtil.toJSON(message);
    }


    @ResponseBody("/wx/isAllUserInfo.do")
    public String findUserInfo(HttpServletRequest request, HttpServletResponse response){
         User userInfo = UserUtil.getUserInfo(request.getSession());
        // 通过session获取不了信息，只能获取手机号
        String phoneNumber = userInfo.getPhoneNumber();
        User user = UserService.findByPhoneNumber(phoneNumber);
        Message msg = null;
        if (user.getUsername() == null){
            // 用户信息不完善
            msg = new Message(-1,"用户信息不完整",user);
        } else{
            msg = new Message(0,"信息完整",user);
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/userInfo_createCode.do")
    public String userInfo_createCode(HttpServletRequest request, HttpServletResponse response){
        int code = RandomUtil.getCode();
        code = 666666;
        HttpSession session = request.getSession();
        session.setAttribute(UserUtil.getUserPhone(session),code+"");
        boolean b = SMSUtil.sendLoginCode(UserUtil.getUserPhone(session), code + "");
        Message msg = null;
        if (b) {
            msg = new Message(0,"验证码发送成功");
        } else {
            msg = new Message(-1,"验证码发送失败");
        }
        return JSONUtil.toJSON(msg);
    }

    @ResponseBody("/wx/updateUserInfo.do")
    public String updateUserInfo(HttpServletRequest request, HttpServletResponse response){
        String userPhone = request.getParameter("userPhone");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        int id = Integer.parseInt(request.getParameter("id"));
        String msg = request.getParameter("msg");
        //验证
        HttpSession session = request.getSession();
        Object code = (String) session.getAttribute(UserUtil.getUserPhone(session));
        Message m = null;
        if (code.equals(msg)){
            // 验证成功
            User user = new User(username, password, null, userPhone);
            boolean update = UserService.update(id, user);
            if (update) {
                m = new Message(0,"信息保存成功");
                // 更新session值
                User userSession = UserUtil.getUserInfo(session);
                userSession.setUsername(user.getUsername());
                userSession.setPassword(user.getPassword());
                userSession.setPhoneNumber(user.getPhoneNumber());
                UserUtil.setUserInfo(session,userSession);
            } else {
                m = new Message(-1,"信息更改失败");
            }
        } else{
            // 验证失败
            m = new Message(-1,"验证码有误请重新输入");
        }

        return JSONUtil.toJSON(m);
    }

    @ResponseBody("/wx/insertUser.do")
    public String insertUser(HttpServletRequest request, HttpServletResponse response){
        String phone = request.getParameter("phoneNumber");
        String password = request.getParameter("password");
        boolean insert = UserService.insert(new User(null, password, null, phone));
        Message e = null;
        if (insert){
            e = new Message(0,"添加成功");
        } else{
            e = new Message(-1,"添加失败");
        }
        return JSONUtil.toJSON(e);
    }

}
